package com.lecture.springlecture.config;

import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.kie.spring.KModuleBeanFactoryPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

@Configuration
public class DroolsConfiguration {

    private static final String RULES_PATH = "rules/";

    @Bean
    @ConditionalOnMissingBean(KieFileSystem.class)
    public KieFileSystem getKieFileSystem() {
        KieFileSystem kieFileSystem = KieServices.Factory.get().newKieFileSystem();
        for (Resource ruleFile : getRuleFiles()) {
            kieFileSystem.write(ResourceFactory.newClassPathResource(RULES_PATH + ruleFile.getFilename(),"UTF-8"));
        }
        return kieFileSystem;
    }

    @Bean
    @ConditionalOnMissingBean(KieContainer.class)
    public KieContainer getKieContainer() {
        KieRepository repository = KieServices.Factory.get().getRepository();
        repository.addKieModule(repository::getDefaultReleaseId);
        KieBuilder kieBuilder = KieServices.Factory.get().newKieBuilder(getKieFileSystem());
        kieBuilder.buildAll();
        return KieServices.Factory.get().newKieContainer(repository.getDefaultReleaseId());
    }

    @Bean
    @ConditionalOnMissingBean(KieSession.class)
    public KieBase getKieBase() {
        return getKieContainer().getKieBase();
    }

    @Bean
    @ConditionalOnMissingBean(KieSession.class)
    public KieSession getKieSession() {
        return getKieContainer().newKieSession();
    }

    @Bean
    @ConditionalOnMissingBean(KModuleBeanFactoryPostProcessor.class)
    public KModuleBeanFactoryPostProcessor getKModuleBeanFactoryPostProcessor() {
        return new KModuleBeanFactoryPostProcessor();
    }


    //获取规则文件
    private Resource[] getRuleFiles() {
        Resource[] resources = new Resource[0];
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        try {
            resources = resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "**/*.*");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resources;
    }
}
